package com.lilihub.miaosha.service;

import com.lilihub.miaosha.common.CodeMsg;
import com.lilihub.miaosha.dao.MiaoshaUserDao;
import com.lilihub.miaosha.domain.MiaoshaUser;
import com.lilihub.miaosha.exception.GlobalException;
import com.lilihub.miaosha.redis.MiaoshaUserKey;
import com.lilihub.miaosha.util.MD5Util;
import com.lilihub.miaosha.util.UUIDUtil;
import com.lilihub.miaosha.vo.LoginVo;
import com.sun.org.apache.bcel.internal.classfile.Code;
import javafx.beans.binding.BooleanExpression;
import jdk.nashorn.internal.parser.Token;
import org.apache.coyote.OutputBuffer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.net.CookieHandler;
import java.text.CollationKey;

/**
 * @BelongsProject: miaosha2
 * @BelongsPackage: com.lilihub.miaosha.service
 * @Author: LiYing
 * @CreateTime: 2021-04-25 11:20
 * @Description:
 */
@Service
public class MiaoshaUserService {

    public static final String COOKI_NAME_TOKEN = "token";

    @Autowired
    private MiaoshaUserDao miaoshaUserDao;

    @Autowired
    private RedisService redisService;

    public MiaoshaUser getById(long id){

        //取缓存
        MiaoshaUser user = redisService.get(MiaoshaUserKey.getById,""+id,MiaoshaUser.class);
        if (user != null){
            return user;
        }

        //取数据库
        user = miaoshaUserDao.getById(id);
        if (user != null){
            redisService.set(MiaoshaUserKey.getById,""+id,user);
        }

        return user;
    }


    public boolean updatePassword(String token, long id, String formPass){

        //取user
        MiaoshaUser user = miaoshaUserDao.getById(id);
        if (user == null){
            throw new GlobalException(CodeMsg.USER_EMPTY);
        }
        //更新数据库
        MiaoshaUser toBeUpdate = new MiaoshaUser();
        toBeUpdate.setId(id);
        toBeUpdate.setPassword(MD5Util.formPassfToDBPass(formPass,user.getSalt()));

        miaoshaUserDao.update(toBeUpdate);

        //处理缓存----否则会出现缓存不一致的情况
        redisService.delete(MiaoshaUserKey.getById,""+id);
        //更新token
        user.setPassword(toBeUpdate.getPassword());
        redisService.set(MiaoshaUserKey.token,token,user);

        return true;
    }



    //登录
    public String login(LoginVo loginVo, HttpServletResponse response) {

        if (loginVo == null){
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }

        String formPass = loginVo.getPassword();
        String phone = loginVo.getPhone();

        //判断手机号是否存在
        MiaoshaUser user = this.getById(Long.parseLong(phone));
        if(user == null) {
            throw new GlobalException(CodeMsg.PHONE_EMPTY);
        }

        //验证密码
        String dbPassword = user.getPassword();
        String dbSalt = user.getSalt();

        String calpass = MD5Util.formPassfToDBPass(formPass, dbSalt);

        if (!calpass.equals(dbPassword)){
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }

        //生成cookie
        String token = UUIDUtil.uuid();

       addCookie(user,response,token);

        return token;

    }

    public MiaoshaUser getbyToken(String token,HttpServletResponse response) {

        //参数验证
        if (StringUtils.isEmpty(token)){
            return null;
        }

        MiaoshaUser user = redisService.get(MiaoshaUserKey.token, token, MiaoshaUser.class);

        //延长有效期,生成一个新的cookie，达到延长效果
        if (user != null) {
            addCookie(user, response,token);
        }
        return user;
    }


    private void addCookie(MiaoshaUser user,HttpServletResponse response,String token){

        redisService.set(MiaoshaUserKey.token,token,user);   //将用户信息和token放入redis中

        Cookie cookie = new Cookie(COOKI_NAME_TOKEN, token);
        cookie.setMaxAge(MiaoshaUserKey.token.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);

    }


}
